package com.blockmeta.bbs.immodule.fragment;


import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.businesslibrary.base.fragment.BaseLazyFragment;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseImResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.immodule.Constants;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.activity.CustomerServiceActivity;
import com.blockmeta.bbs.immodule.activity.FriendRequestsActivity;
import com.blockmeta.bbs.immodule.activity.TemporaryFriendActivity;
import com.blockmeta.bbs.immodule.activity.chat.UUChatActivity;
import com.blockmeta.bbs.immodule.adapter.ContactsFriendsAdapter;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.bean.beaninterface.IFriendsEntry;
import com.blockmeta.bbs.immodule.bean.sort.PinyinComparator;
import com.blockmeta.bbs.immodule.corebean.IMMetaBase;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.immodule.dao.Todo;
import com.blockmeta.bbs.immodule.eventbus.UserInfoChangeEvent;
import com.blockmeta.bbs.immodule.net.api.TemporaryFriendApi;
import com.blockmeta.bbs.immodule.net.pojo.IMUserEntityBook;
import com.blockmeta.bbs.immodule.net.pojo.TemporaryFriendsResponse;
import com.blockmeta.bbs.immodule.utils.HanziToPinyin;
import com.blockmeta.bbs.immodule.widget.SideBar;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;

import static com.blockmeta.bbs.immodule.Constants.CANCHOOSE;
import static com.blockmeta.bbs.immodule.Constants.CHOOSESINGLE;

/**
 * @author airthor
 * @date 2019/3/4
 * A simple {@link Fragment} subclass.
 * 通讯录我的好友
 */
public class FriendsFragment extends BaseLazyFragment implements SideBar.OnTouchingLetterChangedListener, View.OnClickListener {

    @BindView(R2.id.rcv_friends)
    RecyclerView mRcvFriends;
    @BindView(R2.id.group_dialog)
    TextView mGroupDialog;
    @BindView(R2.id.sidebar)
    SideBar mSidebar;

    private View mFriendsRequest, mTemporarySession, mCustomerService;
    private TextView mFriendsRequestCount, mTemporarySessionCount;
    private ImageView mFriendsRequestHint;

    private List<IFriendsEntry> mFriendsEntries = new ArrayList<>();
    public ContactsFriendsAdapter mFriendsAdapter;
    private boolean mCanChoose;
    private boolean mChooseSingle;

    public static FriendsFragment newInstance(boolean canChoose, boolean chooseSingle) {
        FriendsFragment f = new FriendsFragment();
        f.setArguments(buildArgs(canChoose, chooseSingle));
        return f;
    }

    public static Bundle buildArgs(final boolean canChoose, boolean chooseSingle) {
        Bundle bundle = new Bundle();
        bundle.putBoolean(CANCHOOSE, canChoose);
        bundle.putBoolean(CHOOSESINGLE, chooseSingle);
        return bundle;
    }

    public List<IFriendsEntry> getFriendsEntries() {
        return mFriendsEntries;
    }

    @Override
    public View setContentView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_friends, container, false);
    }

    @Override
    protected void initializeLayout() {
        IMApplicationContext.getIMMetaService().register(this);
        EventBus.getDefault().register(this);

        mCanChoose = getArguments().getBoolean(CANCHOOSE);
        mChooseSingle = getArguments().getBoolean(CHOOSESINGLE);
        mSidebar.setOnTouchingLetterChangedListener(this);
        mSidebar.bringToFront();
        mSidebar.setTextView(mGroupDialog);

        mRcvFriends.setLayoutManager(new LinearLayoutManager(mContext));
        ((SimpleItemAnimator) mRcvFriends.getItemAnimator()).setSupportsChangeAnimations(false);
        mFriendsAdapter = new ContactsFriendsAdapter(R.layout.item_contacts_friends, mFriendsEntries);
        View header = LayoutInflater.from(mContext).inflate(R.layout.item_contacts_friend_header, null);
        mFriendsAdapter.bindToRecyclerView(mRcvFriends);
        mFriendsAdapter.setEditable(mCanChoose, mChooseSingle);
        if (!mCanChoose) {
            mFriendsAdapter.addHeaderView(header);
        }

        mFriendsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mCanChoose) {
                    mFriendsAdapter.checkChange(position);

                } else {
                    Intent intent = new Intent(mContext, UUChatActivity.class);
                    intent.putExtra(Params.USER_TAG, mFriendsEntries.get(position).getUserId());
                    startActivity(intent);
                }
            }
        });

        mFriendsRequest = header.findViewById(R.id.v_friends_request);
        mTemporarySession = header.findViewById(R.id.v_temporary_session);
        mCustomerService = header.findViewById(R.id.v_customer_service);
        mFriendsRequestCount = header.findViewById(R.id.tv_friends_request_count);
        mTemporarySessionCount = header.findViewById(R.id.tv_temporary_session_count);
        mFriendsRequestHint = header.findViewById(R.id.iv_friends_request_hint);

        mFriendsRequest.setOnClickListener(this);
        mTemporarySession.setOnClickListener(this);
        mCustomerService.setOnClickListener(this);
        bindTempTalkNum();
        bindFriendAddData();
        doNetWork();
    }

    @Override
    protected void netWork() {

    }


    public void bindFriendAddData() {
        //查询新的好友请求的个数
        long count = IMApplicationContext.getTodoDomainService().getAddFriendUnDoTodoCount(AccountHelper.getUidInt());
        mFriendsRequestCount.setText(String.format("新的好友(%s)", count));
        bindAddFriendRequestTip();
    }

    private void bindTempTalkNum() {
        //查询临时回话
        RetrofitFactory.getRetrofit().create(TemporaryFriendApi.class)
                .getTemporaryFriend(AccountHelper.getUidInt())
                .compose(RxUtil.<BaseImResponse<List<TemporaryFriendsResponse>>>rxSchedulerHelper())
                .compose(RxUtil.<List<TemporaryFriendsResponse>>commonResult())
                .subscribe(new CommonSubscriber<List<TemporaryFriendsResponse>>(mContext) {
                    @Override
                    public void onNext(List<TemporaryFriendsResponse> responses) {
                        if (responses == null) {
                            return;
                        }
                        mTemporarySessionCount.setText(String.format("临时会话(%s)", String.valueOf(responses.size())));
                    }
                });
    }

    private void bindAddFriendRequestTip() {
        //获取上次进入查看后最后一条todo的时间，如果和当前的时间相同就不显示红点
        Todo addFriendLasteatUnCompleteTodo = IMApplicationContext.getTodoDomainService().getAddFriendLasteatUnCompleteTodo(AccountHelper.getUidInt());
        Long lastToDoTime = SharedPreferenceUtil.getLong(mContext, Constants.ADD_FRIEND_LASTTODO_TIME + AccountHelper.getUidInt(), 0);
        if (addFriendLasteatUnCompleteTodo != null && addFriendLasteatUnCompleteTodo.getCreateDate() > lastToDoTime) {
            mFriendsRequestHint.setVisibility(View.VISIBLE);
        } else {
            mFriendsRequestHint.setVisibility(View.GONE);
        }
    }


    @Override
    public void onTouchingLetterChanged(String s) {
        mFriendsAdapter.scrollToTargetLetter(s);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.v_friends_request) {
            startActivity(new Intent(mContext, FriendRequestsActivity.class));
            mFriendsRequestHint.setVisibility(View.GONE);

        } else if (i == R.id.v_temporary_session) {
            startActivity(new Intent(mContext, TemporaryFriendActivity.class));

        } else if (i == R.id.v_customer_service) {
            startActivity(new Intent(mContext, CustomerServiceActivity.class));
        } else {
        }
    }

    //由上层页面收到事件后调用设置数据！
    public void doNetWork() {
        if(!AccountHelper.isLogin()){
            return;
        }
        mFriendsEntries.clear();
        List<IMUserEntity> friends = IMApplicationContext.getUserDomainService().getBookListFriends(AccountHelper.getUidInt());
        for (IMUserEntity friend : friends) {
            IMUserEntityBook friendsBook = new IMUserEntityBook();
            friendsBook.setLetter(HanziToPinyin.getInstance().getLetter(TextUtils.isEmpty(friend.getRemarkName())
                    ? friend.getName() : friend.getRemarkName()));
            friendsBook.setName(friend.getName());
            friendsBook.setRemarkName(friend.getRemarkName());
            friendsBook.setUserId(friend.getUserId());
            friendsBook.setAvatarPath(friend.getAvatarPath());
            friendsBook.setIsFriend(friend.getIsFriend());
            friendsBook.setUserLevel(friend.getUserLevel());
            friendsBook.setDate(friend.getDate());
            mFriendsEntries.add(friendsBook);
        }
        Collections.sort(mFriendsEntries, new PinyinComparator());
        mFriendsAdapter.notifyDataSetChanged();
    }

    public List<IFriendsEntry> getCheckedItems() {
        return mFriendsAdapter.getCheckedItems();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_AddFriends event) {
        doNetWork();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_DeleteFriends event) {
        doNetWork();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_FriendList event) {
        bindTempTalkNum();
        bindFriendAddData();
        doNetWork();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(final UserInfoChangeEvent msg) {
        doNetWork();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_FriendRequestAdd event) {
        bindFriendAddData();
    }

    @Subscribe
    public void onEvent(IMMetaBase.Event_MayBeTempTalkAdd event) {
        bindTempTalkNum();
    }

//    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
//    public void loginUI(MsgSuccess msgSuccess) {
//        if (msgSuccess.login.equals("LOGIN") && !AccountHelper.isLogin()) {
//            //退出登陆
//        } else if (msgSuccess.login.equals("LOGIN") && AccountHelper.isLogin()) {
//            bindTempTalkNum();
//            bindFriendAddData();
//            doNetWork();
//        }
//    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        IMApplicationContext.getIMMetaService().unregister(this);
        super.onDestroy();
    }
}
